import express from "express";
import cookieParser from "cookie-parser";
import favicon from "serve-favicon";

import morgan from "morgan";
import path from "path";
import view from "./view.js";
export default async function (app, config) {
  const { logger, APP_PATH, cookieKey, statics, JSON_LIMIT, appName, version } =
    config;

  app.use(morgan(logger.level));
  app.use(favicon(path.join(APP_PATH, "public/favicon.ico")));
  app.use(cookieParser(cookieKey));
  app.use(express.json({ limit: JSON_LIMIT }));
  app.use(express.urlencoded({ extended: false }));
  view(app, config);
  if (statics.length > 0) {
    statics.forEach((item) => {
      const { prefix, dir, maxAge } = item;
      app.use(prefix, express.static(dir, { maxAge: maxAge || 0 }));
    });
  }

  app.use((req, res, next) => {
    res.setHeader("Create-By", "Chanjs");
    res.setHeader("X-Powered-By", "ChanCMS");
    res.setHeader("ChanCMS", version);
    res.setHeader("Server", appName);
    next();
  });
};
